//
//  WBMainViewController.swift
//  WeiBoApp
//
//  Created by CrazyHacker on 16/6/29.
//  Copyright © 2016年 CrazyHacker. All rights reserved.
//

import UIKit
import SVProgressHUD


class WBMainViewController: UITabBarController {
    private var timer: Timer?
    override func viewDidLoad() {
        super.viewDidLoad()
        setupViewControllers()
        setupComposeButton()
        
        updateTimer()
        setupNewFeatureView()
        delegate = self
        /// 注册通知, 监听用户是否登录
        NotificationCenter.default().addObserver(self, selector: #selector(userShodLogon), name: WBUserShouldLogonNotification, object: nil)
    }

    // FIXME: - 按钮监听方法
    @objc private func composeStates() {
        print("compose 按钮\(composeButton)")
    }
    
    // 添加自定义按钮 懒加载
    private lazy var composeButton: UIButton = UIButton.cz_imageButton(
        "tabbar_compose_icon_add",
        backgroundImageName: "tabbar_compose_button")
   
    // MARK: - 用户需要登录的通知监听方法
    @objc private func userShodLogon(notifi:Notification) {
        print("用户需要登录通知方法 --\(notifi)")
        var time = DispatchTime.now()
        // 参数不为nil 说明是过期
        if notifi.object != nil {
            SVProgressHUD.setDefaultMaskType(.black)
            SVProgressHUD.showInfo(withStatus: "账号过期,请重新登录")
            time = DispatchTime.now() + 2
        }
        
        DispatchQueue.main.after(when: time, execute: {
            let nvc = UINavigationController(rootViewController: WBOAuthViewController())
            self.present(nvc, animated: true, completion: nil)
        })
        
    }
    
    deinit {
        // 销毁通知
        timer?.invalidate()
        // 注销通知 - 否则造成野指针
        NotificationCenter.default().removeObserver(self)
    }
}

extension WBMainViewController {
    private func setupNewFeatureView() {
        // 判断当前用户是否登录
        if !WebNetworkTools.shared.userLogon {
            return
        }
       let v = isNewVersion ? WBNewFeatureView.wbNewFeatureView() : WBWelcomeView.welcomeView()
        
        view.addSubview(v)
    
    }
    
    //  计算型属性 可以在Extensions中使用
    private var isNewVersion: Bool {
        let currentVersion = Bundle.main().infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        print("当前版本" + "\(currentVersion)")
        
        let path: String = ("version" as NSString).cz_appendDocumentDir()
        let sandBoxVersion = (try? String(contentsOfFile: path)) ?? ""
         print("沙盒版本" + "\(sandBoxVersion)")
        // 将当前版本号存进沙盒
        _ = try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)

        // 返回两个版本号是否一致  相等时返回true
        return currentVersion != sandBoxVersion
    }
}

// MARK: - UITabBarControllerDelegate
extension WBMainViewController: UITabBarControllerDelegate {
    /// 设置tabBar点击事件的时候, 界面即将跳转实现此方法
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        let index = (childViewControllers as Array).index(of: viewController)
        print(index)
        // 选中索引是0, 要跳转的控制器的索引也是0 --> 滚动到顶部
        if selectedIndex == 0 && selectedIndex == index {
            print("点击的是首页")
        }
        print("将要选中的控制器\(viewController)")
        let nvc = childViewControllers[0] as! UINavigationController
        let vc = nvc.childViewControllers[0] as! WBHomeViewController
        
        // 让视图滚动到顶部
        vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
        
        // 延迟加载就是为了, 规避当前视图滚动到顶部再刷新数据, 否则两者同时进行,会造成滚动位置的偏差
        DispatchQueue.main.after(when: DispatchTime.now() + 1) { 
            vc.loadData()
        }
        
        vc.tabBarItem.badgeValue = nil
        UIApplication.shared().applicationIconBadgeNumber = 0
        // 如果选中的控制器不是UIViewcontroller 则不跳转
        return !viewController .isMember(of: UIViewController.self)
    }
    
}

extension WBMainViewController {
    
   private func updateTimer() {
    if !WebNetworkTools.shared.userLogon {
        return
    }
    timer = Timer.scheduledTimer(timeInterval: 15, target: self, selector: #selector(checkUnReadCount), userInfo: nil, repeats: true)
    }
    
    @objc private func checkUnReadCount() {
        
        WebNetworkTools.shared.unreadCount { (unReadCount) in
            self.tabBar.items?[0].badgeValue = unReadCount > 0 ? "\(unReadCount)" : nil
            // 设置程序启动图标显示的badgeNumber
            UIApplication.shared().applicationIconBadgeNumber = unReadCount
        }
    }
}


// MARK: - 添加底部按钮
extension WBMainViewController {
    private func setupComposeButton() {
        // tabBar 添加个自定义的视图 -- UIButton 也是继承自UIView
        tabBar.addSubview(composeButton)
        // 布局控件的位置
        let count = CGFloat(childViewControllers.count)
        let width = tabBar.bounds.width / count
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * width, dy: 0)
        
        composeButton.addTarget(self, action: #selector(composeStates), for: .touchUpInside)
    }
}

// MARK: - 添加tabBar自控制器
extension WBMainViewController {
    
    // MARK: - 添加自控制器
    private func setupViewControllers() {
        
        // 1.先从沙盒加载 -- 本地
        let sandBoxPath = dictPath()
        var data = NSData(contentsOfFile: sandBoxPath)
        
        if data == nil {
            // 2.那就从bundle加载 data
            let bundlePath = Bundle.main().pathForResource("main.json", ofType: nil)
            data = NSData(contentsOfFile: bundlePath!)
            
        }

        // 3.反序列化 -- data不一定有值 需要守护
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: AnyObject]] else {
            return
        }
        
        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(setupChildControllers(dict: dict))
        }
        
        viewControllers = arrayM
    }
    /// 返回一个沙盒路径
    func dictPath()-> String {
        // 返回文档目录
        let dictPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        
        let path = (dictPaths as NSString).appendingPathComponent("main.json")
        return path
    }
    
    // MARK: - 使用字典 实例化子控制器 [clsName title imageName]
    private func setupChildControllers(dict:[String: AnyObject])->UIViewController {
        
         // 取得字典内容 tabbar_home_selected
        guard let clsName = dict["clsName"] as? String,
        title = dict["title"] as? String,
            imageName = dict["imageName"] as? String,
        cls = NSClassFromString(Bundle.main().namespace + "." + clsName) as? UIViewController.Type,
        visitInfo = dict["visitorInfo"] as? [String: String]
            
        else {
            return UIViewController()
        }
        
        let vc = cls.init() as! WBBaseViewController
        vc.title = title
        vc.visitInfoDict = visitInfo
        vc.tabBarItem.image = UIImage(named: "tabbar_"+imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_"+imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        // 设置tabbar 文本属性
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange()], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 13)], for: UIControlState(rawValue:0))
        
        let nvc = WBNavigationController(rootViewController:vc)
        return nvc
    }
}
